var express 		= require('express');
var mysql   		= require('mysql');
var config  		= require('../config.json');
var sqlconfig 		= config.mysql;
var router  		= express.Router();
var pool    		= mysql.createPool(sqlconfig);

/*
  Name: data
  Args:
	data:data to be return
	res :response to write data
  Return : 
	Valid String for Client to use
  Description：
	  Return the valid  Data String to client if there is no error
*/

function data(data,res)
{
	console.log("LOG:RESPONSE:"+data);
	return res.end(JSON.stringify({err:0,response:data}));
}

/*
  Name: error
  Args:
	res:response to write err
	err:error message to return
	errcode: description of an error
  Return : 
	Valid String for Client to use
  Description：
	Return the error message to the client 
*/

function error(err,errcode,res)
{
	console.log("LOG:ERROR:"+errcode);
	return res.end(JSON.stringify({err : err,errcode : errcode}));
}

/*
  Name: BeforeAspect 
  Args: 
	request:Object
  Return: 
	data return from this aspect
  Description:
	preprocessor
*/

function BeforeAspect(request)
{
	
	console.log("LOG:REQUEST:"+JSON.stringify(request));
	return request;
}

/*
  Name:Student_Get_All[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	student or parents get all honor
*/

function Student_Get_All_Honor(req,res,next)
{
	var query = "SELECT * from honor where stu_id = ?;"
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'PARENT' && req.session.user_type != 'STUDENT')
		{
			error(403,"Permission Denied",res);
			return;
		}

		var query_args = [];
		query_args.push(req.session.user['stu_id']);
		
		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(300,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}


/*
  Name:Student_Get_Honor_By_Type[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	student or parents get honor by type
 */

function Student_Get_Honor_By_Type(req,res,next)
{
	var query = "SELECT * from honor where stu_id = ? and honor_type = ?;";
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'PARENT' && req.session.user_type != 'STUDENT')
		{
			error(403,"Permission Denied",res);
			return;
		}

		if (typeof(args['honor_type']) != 'number') {

			error(401,"Invalid Argument",res);
			return;		
		}

		var query_args = [];
		query_args.push(req.session.user['stu_id']);
		query_args.push(args['honor_type']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}


/*
  Name:Student_Get_Honor_By_Date[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	student or parents get  honor  by year(&semester)
*/
function Student_Get_Honor_By_Date(req,res,next){
    
    var query = "SELECT * from honor where stu_id = ? and honor_year = ?;";
    var query_args = [];
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}
		if(req.session.user_type != 'PARENT' && req.session.user_type != 'STUDENT')
		{
			error(403,"Permission Denied",res);
			return;
		}

		query_args.push(req.session.user['stu_id']);

		if(typeof(args['honor_year']) != 'number') 
		{
			error(401,"Invalid Argument",res);
			return;
	    	}
		else 
		{
			query_args.push(args['honor_year']);			
		}
		if (typeof(args['honor_semester']) == 'number') 
		{
			query = "SELECT * from honor where stu_id = ? and honor_year = ? and honor_semester = ?";
			query_args.push(args['honor_semester']);
		}
		
		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}



/*
  Name:Teacher_Get_All[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	teacher get all honor
*/

function Teacher_Get_All_Honor(req,res,next)
{
	var query = "SELECT * from honor where stu_id = ?;"
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}
		
		if(typeof(args['stu_id']) != 'number'){
            
            error(401,"Invalid Argument",res);
			return;		
		}

		var query_args = [];
		query_args.push(args['stu_id']);
		
		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(300,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}


/*
  Name:Teacher_Get_Honor_By_Type[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Teacher get  honor by type
*/

function Teacher_Get_Honor_By_Type(req,res,next)
{
	var query = "SELECT * from honor where stu_id = ? and honor_type = ?;";
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}

		if (typeof(args['stu_id']) != 'number' || typeof(args['honor_type']) != 'number') {

			error(401,"Invalid Argument",res);
			return;		
		}

		var query_args = [];
		query_args.push(args['stu_id']);
		query_args.push(args['honor_type']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}


/*
  Name:Student_Get_Honor_By_Date[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	student or parents get  honor  by year(&semester)
*/

function Teacher_Get_Honor_By_Date(req,res,next){
    
    var query = "SELECT * from honor where stu_id = ? and honor_year = ?;";
    var query_args = [];
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}

	    if (typeof(args['stu_id']) !='number' || typeof(args['honor_year']) != 'number') {
                           
               query_args.push(args['stu_id']);
		       query_args.push(args['honor_year']);

               if (typeof(args['honor_semester']) == 'number') {
               	       query = "SELECT * from honor where stu_id = ? and honor_year = ? and honor_semester = ?";
                       query_args.push(args['honor_semester']);
                    };

	    }else {

	    	error(401,"Invalid Argument",res);
			return;		
	    }
		

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}


/*
  Name:Teacher_Add_Honor[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
			stu_id 		: student to add honor
			honor_type 	: type to add honor to
			honor_content 		: content
			honor_semester	: honor_semester
			honor_year	: honor_year
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Add honor info to a student 
*/

function Teacher_Add_Honor(req,res,next)
{
	var query = "INSERT INTO honor SET ?;";
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}

		var query_args = {};

		if(typeof(args['stu_id']) != 'number' 
			|| typeof(args['honor_type']) != 'number' 
			|| typeof(args['honor_content']) != 'string' 
			|| typeof(args['honor_semester']) != 'number' 
			|| typeof(args['honor_year']) != 'number' 
			)
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{
			query_args['stu_id']	= args['stu_id'];
			query_args['honor_type']= args['honor_type'];
			query_args['honor_content']	= args['honor_content'];
			query_args['honor_semester'] = args['honor_semester'];
			query_args['honor_year']= args['honor_year'];
		}

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}

/*
  Name:Teacher_Delete_Honor[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
			score_id: hw_id of score entity to delete 
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Delete honor of a student
*/

function Teacher_Delete_Honor(req,res,next)
{
	var query = "DELETE FROM honor WHERE honor_id = ?;";
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}

		var query_args = [];

		if(typeof(args['honor_id']) != 'number' )
		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{
			query_args.push(args['honor_id']);
		}

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}

/*
  Name:Teacher_Modify_honor[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
			stu_id 		: student to add honor
			honor_type 	: type to add honor to
			honor_content 		: content
			honor_semester	: honor_semester
			honor_year	: honor_year
			honor_id:
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Modify Honor 
*/

function Teacher_Modify_Honor(req,res,next)
{
	var query = "UPDATE honor SET honor_content = ? ,honor_type = ?,honor_semester = ?,honor_year = ? WHERE honor_id = ?;";
	try{
		var args = BeforeAspect(req.body);
		
		if(typeof(req.session.user) !=  'object' )
		{
			error(402,"Login First",res);
			return;
		}

		if(req.session.user_type != 'TEACHER')
		{
			error(403,"Permission Denied",res);
			return;
		}

		var query_args = [];

		if(typeof(args['honor_id']) != 'number'
			||typeof(args['honor_type']) != 'number'
			||typeof(args['honor_content'])!= 'string'
			||typeof(args['honor_semester']) != 'number'
			||typeof(args['honor_year'])!= 'number'
			)

		{
			error(401,"Invalid Argument",res);
			return;		
		}
		else
		{
			query_args.push(args['honor_content']);
			query_args.push(args['honor_type']);
		    query_args.push(args['honor_semester']);
			query_args.push(args['honor_year']);
			query_args.push(args['honor_id']);
	
		}

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			else
			{
				data(rows,res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}


//Register '/' GET router
router.get('/', function(req, res, next) 
{
  data({},res);
});


//Register all routers 
var functions = {	 "/stu_all/"     	: Student_Get_All_Honor
			,"/stu_scope/by_type"	: Student_Get_Honor_By_Type
			,"/stu_scope/by_date": Student_Get_Honor_By_Date

			,"/tea_all/"     	: Teacher_Get_All_Honor
			,"/tea_scope/by_type"	: Teacher_Get_Honor_By_Type
			,"/tea_scope/by_date" : Teacher_Get_Honor_By_Date	
			,"/tea_add_honor" 	: Teacher_Add_Honor
			,"/tea_del_honor" 	: Teacher_Delete_Honor
			,"/tea_modify_honor" 	: Teacher_Modify_Honor
			}

for(var i in functions) 
{
	console.log("FUNCTION_LOADED(honor):"+i);
	router.post(i, functions[i]);
}

module.exports = router;

